import { Component } from "./Component";

export interface IPoolable {
    onRecycle(): void;
    onReuse():void;
}

/**
 * 需要增加类型限制，为Ipoolable
 */
export class GenericPool<TKey, T extends IPoolable>  {
    private _pool = new Map<TKey, IPoolable[]>(); 

    constructor(private _keyFunc: (item: IPoolable) => TKey) {
    }

    // 获取一个组件
    get(key: TKey) {
        if (!this._pool.has(key)) {
            this._pool.set(key, []);
        }
        let item = this._pool.get(key)?.pop();
        if (item) {
            item.onReuse();
        }
        return item as T;
    }

    // 回收一个组件
    put(item: IPoolable) {
        const key = this._keyFunc(item);
        let pool = this._pool.get(key);
        if (!pool) {
            pool = [];
            this._pool.set(key, pool);
        }
        item.onRecycle();
        pool.push(item);
    }   
}
